package com.geek.framework.study.config.support;


import com.geek.framework.study.common.BaseException;
import com.geek.framework.study.common.EncodedResource;
import com.geek.framework.study.config.microprofile.source.SimpleConfigSource;
import com.geek.framework.study.util.PropertiesUtils;
import org.eclipse.microprofile.config.spi.ConfigSource;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @see ConfigSource
 */
public class DefaultConfigSourceFactory implements ConfigSourceFactory{

    @Override
    public ConfigSource createConfigSource(String name, Integer original,boolean ignoreNotFound, EncodedResource encodedResource) {
        Map<String, String> propertiesMap = parseResource(encodedResource, ignoreNotFound);
        if (propertiesMap == null) {
            return null;
        }
        return new SimpleConfigSource(name, original, propertiesMap);
    }

    @Override
    public ConfigSource createConfigSource(String name, Integer original, boolean ignoreNotFound, List<EncodedResource> encodedResourceList) {
        Map<String, String> propertiesMap = new HashMap<>();
        for (EncodedResource resource : encodedResourceList) {
            Map<String, String> parseResource = parseResource(resource, ignoreNotFound);
            if (parseResource != null) {
                propertiesMap.putAll(parseResource);
            }
        }
        return new SimpleConfigSource(name, original, propertiesMap);
    }

    private Map<String, String> parseResource(EncodedResource encodedResource, boolean ignoreNotFound) {
        try {
            Properties properties = new Properties();
            properties.load(encodedResource.getReader());
            return PropertiesUtils.toStringMap(properties);
        } catch (IOException e) {
            if (ignoreNotFound) {
                return null;
            }else{
                throw new BaseException(e);
            }
        }

    }


}
